<?php

namespace App\Api\Controllers\EasyPay;

use App\Api\Controllers\Config\EasyPayConfigController;
use App\Models\BankInfo;
use App\Models\EasypayaStore;
use App\Models\EasypayStore;
use App\Models\EasypayConfig;
use App\Models\Elec\ElecContracts;
use App\Models\MyBankCategory;
use App\Models\StorePayWay;
use App\Models\VbillStoreCategory;
use App\Util\UploadImgUtil;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class MerchantController extends BaseController
{
    public static $key;
    public static $client_code;

    public $domain = "";

    const DOAMIN_PRO = "https://mms.eycard.cn";

    const DOMAIN_DEV = "https://mtest.eycard.cn:4443";

    //联合收单
    const DOMAIN_LIANHE = "https://phoenix.eycard.cn";

    const APPLAY = '/AG_MerchantManagementSystem_Core/agent/api/gen';


    const IMG_UPDATE = '/AG_MerchantManagementSystem_Core/agent/api/imgUpl';


    const APPLY_QUERY = '/yqt/merchant/marketing/detailQuery';

    const ACT_QUERY = '/yqt/merchant/marketing/query';

//    const IMG_UPDATE = 'https://mtest.eycard.cn:4443/AG_MerchantManagementSystem_Core/agent/api/imgUpl';
//    const APPLAY = 'https://mms.eycard.cn/AG_MerchantManagementSystem_Core/agent/api/gen';
////    const APPLAY = 'https://mtest.eycard.cn:4443/AG_MerchantManagementSystem_Core/agent/api/gen';
///
///
///
//    const IMG_UPDATE = 'https://mms.eycard.cn/AG_MerchantManagementSystem_Core/agent/api/imgUpl';
//
//    const APPLY_QUERY = 'https://d-phoenix-gap.easypay.com.cn:24443/yqt/merchant/marketing/detailQuery';
//    const ACT_QUERY = 'https://phoenix.eycard.cn/yqt/merchant/marketing/query';

    public function __construct(int $config_id = 1234)
    {
        $config = EasypayConfig::query()->where([
            'config_id' => $config_id,
        ])
            ->select('key', 'client_code')
            ->first();
        if ($config) {
            self::$key = $config->key;
            self::$client_code = $config->client_code;
        }
        if (env("APP_ENV") == "dev") {
            $this->domain = self::DOMAIN_DEV;
        } else {
            $this->domain = self::DOAMIN_PRO;
        }

    }

    //进件
    public function apply(string $version, array $info)
    {
        $query = EasypayStore::query();
        if ($version == "easypaya") {
            $query = EasypayaStore::query();
        }

        $easypay_store = $query->where([
            'store_id' => $info['store']->store_id,
        ])
            ->select('mer_trace', 'audit_status')
            ->first();
        //是否已经进件
        if ($easypay_store) {
            if ($easypay_store->audit_status == 3) {
                return json_encode([
                    'status' => 2,
                    'message' => '审核中1'
                ]);
            }
            if ($easypay_store->audit_status == 0) {
                return json_encode([
                    'status' => 1,
                    'message' => '审核成功'
                ]);
            }
        }

        $easypay_config_obj = new EasyPayConfigController();
        $easypay_config = $easypay_config_obj->easypay_config($info['store']->config_id);
        if (!$easypay_config) {
            return json_encode([
                'status' => 2,
                'message' => '易生支付配置不存在请检查配置'
            ]);
        }
        $Store = $info['store'];
        $StoreBank = $info['bank'];
        $easypay_images = $info['img'];


        if ($Store->store_type == '1') { //1-个体工商户
            $mer_mode = '1';
        } elseif ($Store->store_type == '2') { //2-企业
            $mer_mode = '0';
        } else { //3-小微商户
            $mer_mode = '2';
        }

        $pic_info_list = [];
        if ($Store->store_type != '3') { //非个人,企业（0）或者个体户（1）时，需要传：05-营业执照
            $pic_info_list[] = [
                'picMode' => '05',
                'fileId' => $this->updateImg($easypay_images->store_license_img, '05') //营业执照
            ];
        }

        //对私结算
        if ($StoreBank->store_bank_type == '01') {
            //需要传：15-清算授权书
            if ($Store->cert_of_auth) {
                $pic_info_list[] = [
                    'picMode' => '15',
                    'fileId' => $this->updateImg($Store->cert_of_auth, '15')//
                ];
            }
            if (!empty($easypay_images->bank_img_a)) {
                $pic_info_list[] = [
                    'picMode' => '14', //14-银行卡
                    'fileId' => $this->updateImg($easypay_images->bank_img_a, '14')//
                ];
            }
        } else {
            //对公结算，需要传：13-开户许可证；
            $pic_info_list[] = [
                'picMode' => '13',
                'fileId' => $this->updateImg($easypay_images->store_industrylicense_img, '13')//
            ];
            $pic_info_list[] = [
                'picMode' => '09', //09-门牌号；
                'fileId' => $this->updateImg($easypay_images->store_other_img_c, '09'),//
            ];
        }
        $mer_area = '';
        $area = DB::table('easypay_city')->where(['YL_PR_NAME' =>  $Store->city_name])
            ->where(['YL_NAME' => $Store->area_name])->first();
        if(empty($area)){
            $area = DB::table('easypay_city')->where(['YL_PR_NAME' => $Store->province_name . $Store->city_name])
                ->where(['YL_NAME' => $Store->area_name])->first();
        }
        if ($area) {
            $mer_area = $area->YL_CODE;
        }

        $acc_info_bak = '';
        if ($mer_mode == '0' && ($StoreBank->store_bank_type == '01')) {
            $acc_info_bak = []; //结算账户信息2,当商户类型（merMode）为企业商户并且结算账户为对私账户时，该字段必传???
        }

        $MyBankCategory = MyBankCategory::where('category_id', $Store->category_id)
            ->first();
        if (!$MyBankCategory) {
            $MyBankCategory = VbillStoreCategory::where('id', $Store->category_id)
                ->first();
        }
        if (!$MyBankCategory) {
            return json_encode([
                'status' => 2,
                'message' => '请选择正确的门店类目'
            ]);
        }


        $picInfoList = [ //图片信息
            [
                'picMode' => '01', //图片类型,01 - 法人身份证正面 ；05-营业执照；13-开户许可证；14-银行卡；15-清算授权书；16-定位照（选填）；17-手持身份证照片（选填）
                'fileId' => $this->updateImg($easypay_images->head_sfz_img_a, '01'), //图片唯一ID
            ],
            [
                'picMode' => '02', //02-法人身份证反面；
                'fileId' => $this->updateImg($easypay_images->head_sfz_img_b, '02'),
            ],
            [
                'picMode' => '03', //03-商户联系人身份证正面；
                'fileId' => $this->updateImg($easypay_images->head_sfz_img_a, '03'),//
            ],
            [
                'picMode' => '04', //04-商户联系人身份证反面；
                'fileId' => $this->updateImg($easypay_images->head_sfz_img_b, '04'),//
            ],
            [
                'picMode' => '06', //06-收银台；
                'fileId' => $this->updateImg($easypay_images->store_img_a, '06'),
            ],
            [
                'picMode' => '07', //07-内部环境照；
                'fileId' => $this->updateImg($easypay_images->store_img_b, '07'),
            ],
            [
                'picMode' => '08', //08-营业场所门头照；
                'fileId' => $this->updateImg($easypay_images->store_logo_img, '08'),
            ],
//            [
//                'picMode' => '09', //09-门牌号；
//                'fileId' => $this->updateImg($easypay_images->house_number,'09'),//
//            ],
//            [//纸质合同--   废弃
//                'picMode' => '10', //10-协议；
//                'fileId' => $this->updateImg($easypay_images->store_other_img_c, '10'),//
//            ],
//            [
//                'picMode' => '11', //11-商户登记表正面；
//                'fileId' => $this->updateImg($easypay_images->merc_regist_form_a,'11'),//
//            ],
//            [
//                'picMode' => '12', //12-商户登记表反面；
//                'fileId' => $this->updateImg($easypay_images->merc_regist_form_b,'12'),//
//            ],

        ];
        Log::channel("easypay")->info("easypay-pic", $picInfoList);
        $funcInfo = [ //商户的功能信息，包括商户的扣率信息，JSON 格式字符串(list)，可以开通 1 个或多个功能,如果需要关闭功能，只需要送对应功能的功能 ID（funcId 字段） 扣率的单位默认按比例（单位%），如果有特殊情况，会在对应的功能里说明
            [ //支付宝
                'funcId' => '2', //功能ID
                'calcVal' => $info['rate_list']['rate'], //扣率
            ],
            [ //微信
                'funcId' => '3', //功能ID
                'calcVal' => $info['rate_list']['rate'], //扣率
            ],
            [ //银联二维码
                'funcId' => '12', //功能ID
                'DStlmType' => '1', //借记卡扣率方式 :1-封顶;0-不封顶???
                'DCalcVal' => '0.6',//$info['rate_list']['rate'], //借记卡扣率???
                'DStlmMaxAmt' => '30', //借记卡封顶金额???
                'DFeeLowLimit' => '0', //借记卡手续费最低值???
                'CCalcVal' => '0.6', //信用卡扣率???
                'CFeeLowLimit' => '0', //信用卡手续费最低值???
            ]
        ];
        //查询结算方式和费率
        $storePayWay=StorePayWay::query()->where("company",$version)->where("store_id",$Store->store_id)->first();
        if($storePayWay->settlement_type=="D0"){
            $funcInfo[]=[ //实时入账
                'funcId' => '25', //功能ID
                'tradeType' => '0', //交易类型：0-全部；1-银行卡；2-条码支付
                'DCalcType' => '0', //借记卡计费类型:0-按笔数（单位：元）;1-按比例（单位：%）???
                'DCalcVal' => (string)$storePayWay->settlement_rate,//$info['rate_list']['rate'], //借记卡扣率???
                'CCalcType' => '0', //信用卡计费类型:0-按笔数（单位：元）;1-按比例（单位：%）???
                'CCalcVal' => (string)$storePayWay->settlement_rate,//$info['rate_list']['rate'], //信用卡扣率???
            ];
        }else if($storePayWay->settlement_type=="D1"){
            $funcInfo[]=[ //实时入账
                'funcId' => '10', //功能ID
                "calcType"=>"1",
                "calcVal"=>"0",
                "payDateType"=>"0",
            ];
        }
        $funcInfo=json_encode($funcInfo);
        $accInfo = json_encode([ //结算账户信息
            'bankName' => $StoreBank->bank_name, //开户行名称
            'bankCode' => $StoreBank->bank_no, //开户行行号
            'account' => $StoreBank->store_bank_no, //账号
            'accName' => $StoreBank->store_bank_name, //账户名称
            'accType' => ($StoreBank->store_bank_type == '02') ? '10' : '00', //账户类型：00-个人；10-对公
//                        'accArea' => '', //O,账户所属区域:区号
            'legalType' => ($StoreBank->store_bank_type == '01') ? '0' : '', //C,证件类型：0-居民身份证或临时身份证;1-外国公民护照;2-港澳居民来往大陆通行证或其他有效旅游证件；3-其他类个人身份有效证件；4-单位证件；5-军人或武警身份证件 accType 为个人时必填
            'legalCode' => ($StoreBank->store_bank_type == '01') ? (!empty($StoreBank->bank_sfz_no) ? $StoreBank->bank_sfz_no : (empty($Store->head_sfz_no) ? "" : $Store->head_sfz_no)) : (empty($Store->head_sfz_no) ? "" : $Store->head_sfz_no), //C,证件号 accType 为个人时必填
            'accPhone' => $Store->people_phone, //C,对私手机号 accType 为个人时必填
        ]);


        $licInfo = [ //营业执照信
            'merLic' => ($mer_mode == '0' || $mer_mode == '1') ? $Store->store_license_no : '', //C，工商注册号/统一社会信用码（营业执照）,merMode 为0,1 时，必传
            'licValidity' => ($mer_mode == '0' || $mer_mode == '1') ? $this->EasyPayTimeFormat($Store->store_license_stime, $Store->store_license_time) : "", //C,营业执照有效期 格式：["起始日期","截止日期"],JSON 格式字符串 ,merMode 为 0,1 时，必传
            'licName' => $Store->store_short_name, //注册名称
            'businScope' => $Store->category_name, //主营业务
            'capital' => '10', //注册资本：单位-万元???
//                        'capitalCurrency' => '', //o,注册资本币种:默认-人民币
            'licAddr' => $Store->province_name . $Store->city_name . $Store->area_name . $Store->store_address, //注册地址
            'controlerName' => $Store->head_name, //控股股东或实际控制人姓名或名称
            'controlerLegalCode' => $Store->head_sfz_no, //控股股东或实际控制人证件号码
            'controlerLegalType' => '0', //控股股东或实际控制人证件种类：0-居民身份证或临时身份证;1-外国公民护照;2-港澳居民来往大陆通行证或其他有效旅游证件；3-其他类个人身份有效证件；4-单位证件；5-军人或武警身份证件
            'controlerLegalValidity' => $this->EasyPayTimeFormat($Store->head_sfz_stime, $Store->head_sfz_time), //控股股东或实际控制人证件有效期
            'controlerCapital' => '', //控股股东或实际控制人证出资金额:单位-万元???
//                        'controlerDate' => '', //o,控股股东或实际控制人出资日期
//                        'controlerRate' => '', //o,控股股东或实际控制人控股股权比例
        ];
        foreach ($licInfo as $k => $v) {
            if ($v == "") {
                unset($licInfo[$k]);
            }
        }
        $licInfo = json_encode($licInfo);

        $merInfo = json_encode([ //商户基本信息，JSON 格式字符串，商户变更的时候，可以只传需要变更的字段
            'merMode' => $mer_mode, //商户类型（0-企业 1-个体户 2-个人）
            'merName' => $Store->store_name, //注册名称
            'businName' => $Store->store_short_name, //经营名称 (店名)
//                        'merEngName' => '', //0,英文名称
            'merType' => $MyBankCategory->mcc, //商户类型（MCC），银联定义的 MCC 编码
            'standardFlag' => '0', //行业大类 0-标准、1-优惠、2-减免
            'merArea' => $mer_area, //商户区域：银联地区码
            'merAddr' => $Store->province_name . $Store->city_name . $Store->area_name . $Store->store_address, //注册地址
            'businBegtime' => '0630', //营业时间：开始时间，格式：HHMM
            'businEndtime' => '2230', //营业时间：结束时间，格式：HHMM
            'employeeNum' => '1', //公司规模:1：0-50 人；2：50-100 人；3:100 以上
            'businForm' => '02', //经营形态：02-普通店、01-连锁店
//                        'conMode' => '0', //o,商户联接方式 1-直联(直联银联的商户)、0-间联（非直联银联的，默认为 0）
//                        'payAccMode' => '0', //o,是否虚拟账户（0-银行账户（默认），1-虚拟账户）
            'stlmType' => '1', //o,是否易生清算：0 -- 挂账， 1 -- 正常清算商户，X--不清算，F--不结算
//                        'merMark' => '', //o,备注
        ]);
        //获取合同信息
        $elec = ElecContracts::query()->where([
            "store_id" => $Store->store_id,
            "api_type" => "easypay",
            "company" => $version,
            "contractState" => "1"
        ])->orderBy("id", "desc")->first();
        if (empty($elec)) {
            return json_encode([
                'status' => 2,
                'message' => '请先签署合同'
            ]);
        }

        $plusInfo = json_encode([ //附加信息，商户的法人身份证等信息
            'merLegal' => $Store->head_name, //法定代表人姓名
            'legalType' => '0', //证件类型：0-居民身份证或临时身份证;1-外国公民护照;2-港澳居民来往大陆通行证或其他有效旅游证件；3-其他类个人身份有效证件；4-单位证件；5-军人或武警身份证件
            'legalCode' => $Store->head_sfz_no, //法人证件号码
            'legalValidity' => $this->EasyPayTimeFormat($Store->head_sfz_stime, $Store->head_sfz_time), //证件有效期 格式：["起始日期","截止日期"],JSON 格式字符串,例如：["2011.01.01","2039.01.01"]
            'legalPhone' => $Store->people_phone, //手机号
//                        'legalMobile' => '', //0,固定电话
            'linkMan' => $Store->people, //商户联系人姓名
            'linkmanType' => '0', //证件类型：0-居民身份证或临时身份证;1-外国公民护照;2-港澳居民来往大陆通行证或其他有效旅游证件；3-其他类个人身份有效证件；4-单位证件；5-军人或武警身份证件
            'linkmanCode' => $Store->head_sfz_no, //证件号码
            'linkmanValidity' => $this->EasyPayTimeFormat($Store->head_sfz_stime, $Store->head_sfz_time), //证件有效期 格式：["起始日期","截止日期"],JSON 格式字符串
            'linkmanPhone' => $Store->people_phone, //手机号
            "contractNo" => $elec->contractNo,//电子协议编号 电子协议与协议图片2选1必传
            "signatoryName" => $elec->signatoryName,//签署方名称 电子协议与协议图片2选1必传
//                        'linkmanMobile' => '', //o,固定电话
//                        'webSite' => '', //o,商户网址
//                        'webName' => '', //o,网站或 APP 名称
//                        'webIcp' => '', //o,ICP 许可证编号
        ]);


        $picInfoList = json_encode(array_merge($pic_info_list, $picInfoList));

        //$picInfoList = '[{"picMode":"01","fileId":"646ec9933e10af0747cfd48a"}, {"picMode":"02","fileId":"646ec9933e10af0747cfd48d"}, {"picMode":"03","fileId":"646ec9933e10af0747cfd48f"}, {"picMode":"04","fileId":"646ec9933e10af0747cfd490"}, {"picMode":"05","fileId":"646ec9933e10af0747cfd492"}, {"picMode":"06","fileId":"646ec9933e10af0747cfd495"}, {"picMode":"07","fileId":"646ec9933e10af0747cfd497"}, {"picMode":"08","fileId":"646ec9933e10af0747cfd498"}, {"picMode":"09","fileId":"646ec9943e10af0747cfd49c"}, {"picMode":"10","fileId":"646326403e10af1de26edbad"}, {"picMode":"11","fileId":"5e6f3acd3e10af350d348125"}, {"picMode":"12","fileId":"5e6f3acd3e10af350d348128"}, {"picMode":"14","fileId":"5e6f3acd3e10af350d348129"}, {"picMode":"15","fileId":"5e6f3acd3e10af350d34812b"}]';

//        $merInfo = '{"merMode":"0","projectBank":"000000","merName":"乌鲁木齐盛世嘉颜贸易有限公司","businName":"乌鲁木齐盛世嘉颜贸易有限公司","merType":"5812","standardFlag":"0","merArea":"7718","merAddr":"注册地址-h","businBegtime":"1800","businEndtime":"0800","employeeNum":"3","businForm":"02","payAccMode":"1"}';
//        $licInfo = '{"merLic":"91460000MA5TM3M35E","licValidity":["2012.01.19","2032.01.19"],"licName":"aadaqw","businScope":"收钱","capital":"1000","licAddr":"美术课地址","controlerName":"张子墨","controlerLegalCode":"230281199702214012","controlerLegalType":"0","controlerLegalValidity":["2012.01.19","2032.01.19"]}';
//        $funcInfo = '[{"funcId":2,"calcVal":"0.38"}, {"funcId":3,"calcVal":"0.38"}, {"funcId":25,"tradeType":"0","DCalcType":"0","DCalcVal":"0.1","CCalcType":"1","CCalcVal":"0"}, {"funcId":12,"DStlmType":"1","DCalcVal":"0.5","DStlmMaxAmt":"28","DFeeLowLimit":"0","CCalcVal":"0.6","CFeeLowLimit":"0"}, {"funcId":14,"DStlmType":"1","DCalcVal":"0.3512","DStlmMaxAmt":"20","DFeeLowLimit":"3.13","CCalcVal":"0.35","CFeeLowLimit":"33.33"}]';
//        $plusInfo = '{"merLegal":"李清荣","legalType":"0","legalCode":"440823197808124914","legalValidity":["2012.01.19","2039.01.01"],"legalPhone":"13121178851","linkMan":"宴银华","linkmanType":"0","linkmanCode":"412728198502104619","linkmanValidity":["2012.01.19","2032.01.19"],"linkmanPhone":"13121178851"}';
//        $accInfo = '{"bankName":"邮政储蓄银行","bankCode":"403100000004","account":"6221803610003002020","accName":"何勇","accType":"00","legalType":"0","legalCode":"342622199004102154","accPhone":"18715101633"}';


        $reqData = [
            'picInfoList' => $picInfoList,
            'merInfo' => $merInfo,
            'operaTrace' => uniqid(),
            'messageType' => 'AGMERAPPLY',
            'backUrl' => url('api/easypay/merchant_apply_notify_url?type=' . $version),
            'clientCode' => $easypay_config->client_code,
            'licInfo' => $licInfo,
            'funcInfo' => $funcInfo,
            'plusInfo' => $plusInfo,
            'version' => '1.0',
            'accInfo' => $accInfo,
        ];

        $reqData['MAC'] = $this->sign($reqData);
        $result = json_decode($this->curl($reqData, $this->domain . self::APPLAY, ['Charset: UTF-8']), true);
//        error_log(date('Y-m-d H:i:s')." 【银盛进件返回】： ".json_encode([$reqData,$result])."\n\n", 3, "/tmp/". 'ys-add-mch'.date('Ymd').".log");
        Log::channel("easypay")->info("易生进件", [
            "reqData" => $reqData,
            "resData" => $result
        ]);
        if ($result && isset($result['retCode']) && $result['retCode'] == '0000') {
            //是否已经进件
            if (!empty($easypay_store)) {
                $easypay_store->operaTrace = $result['operaTrace'];
                $easypay_store->mer_trace = $result['merTrace'];
//                $easypay_store->version = $version;
                $easypay_store->save();
            } else {
                if ($version == "easypay") {
                    EasypayStore::create([
                        'config_id' => 1234, 'operaTrace' => $result['operaTrace'], 'mer_trace' => $result['merTrace'],
                        'store_id' => $Store->store_id,
                    ]);
                } else {
                    EasypayaStore::create([
                        'config_id' => 1234, 'operaTrace' => $result['operaTrace'], 'mer_trace' => $result['merTrace'],
                        'store_id' => $Store->store_id,
                    ]);
                }
            }

            StorePayWay::query()->where([
                "store_id" => $Store->store_id,
                "company" => $version
            ])
                ->where("status", "!=",1)
                ->update([
                    "status" => 2,
                    "status_desc" => "审核中"
                ]);

            return [
                'status' => 2,
                'message' => '审核中2',
            ];
        } else {
            return [
                'status' => 2,
                'message' => $result['retMsg'] . "--------",
            ];
        }
    }

    public function query(Request $request)
    {
        $data = $request->all();
        $storeId = $data['store_id'];
        $ways_type = $data["ways_type"] ?? "";


        if (in_array($ways_type, [21001, 21002, 21004])) {
            $version = "easypay";
        } else if (in_array($ways_type, [61001, 61002, 61004])) {
            $version = "easypaya";
        }


        $easypay_config_obj = new EasyPayConfigController();
        $easypay_config = $easypay_config_obj->easypay_config($storeId);
        if (!$easypay_config) {
            return json_encode([
                'status' => 2,
                'message' => '易生支付配置不存在请检查配置'
            ]);
        }
        $query = EasypayStore::query();
        if ($version == "easypaya") {
            $query = EasypayaStore::query();
        }
        $easypay_store = $query->where('store_id', $storeId)
//            ->select('operaTrace', 'audit_status')
            ->first();
        if (!$easypay_store) {
            return json_encode([
                'status' => 2,
                'message' => '未进件'
            ]);
        }
        if ($easypay_store->audit_status == 0 && !empty($easypay_store->wechatId) && !empty($easypay_store->alipayId)) {
            return json_encode([
                'status' => 2,
                'message' => '审核通过'
            ]);
        }
        $reqData = [
            'operaTrace' => $easypay_store->operaTrace,
            'messageType' => 'QUERYAUDMER',
            'clientCode' => $easypay_config->client_code,
            'version' => '1.0',
        ];

        $reqData['MAC'] = $this->sign($reqData);
        $result = json_decode($this->curl($reqData, $this->domain . self::APPLAY, ['Charset: UTF-8']), true);
//        error_log(date('Y-m-d H:i:s') . " 【银盛进件查询】： " . json_encode([$reqData, $result]) . "\n\n", 3, "/tmp/" . 'ys-add-mch' . date('Ymd') . ".log");
        Log::channel("easypay")->info("query", [
            "url" => $this->domain . self::APPLAY,
            "req" => $reqData,
            "res" => $result
        ]);
        if ($result && isset($result['retCode']) && $result['retCode'] == '0000') {
            if ($result['auditStatus'] == "0") {
                $sysInfo = json_decode($result['sysInfo'], true);
                //获取子商户号
                $funcInfo = json_decode($result['funcInfo'], true);
                $wechatId = $alipayId = '';
                if (is_array($funcInfo)) {
                    foreach ($funcInfo as $v) {
                        if ($v['funcName'] == '支付宝') {
                            $alipayId = $v['alipayId'];
                        }
                        if ($v['funcName'] == '微信') {
                            $wechatId = $v['wechatId'];
                        }
                    }
                }
                Log::channel("easypay")->info("get_sub_merchant", [
                    "funcInfo" => $funcInfo,
                    "wechatId" => $wechatId,
                    "alipayId" => $alipayId
                ]);
                $query->where('operaTrace', $result['operaTrace'])->update([
                    'termMercode' => $sysInfo[0]['termMercode'],
                    'termTermcode' => $sysInfo[0]['termTermcode'],
                    'wechatId' => $wechatId,
                    'alipayId' => $alipayId,
                    'audit_status' => 0,
                    'audit_msg' => '审核通过'
                ]);

                DB::table('store_pay_ways')
                    ->where(['store_id' => $storeId, 'company' => $easypay_store->version])
                    ->update([
                        'status' => 1,
                        'status_desc' => '开通成功',
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ]);
                return json_encode([
                    'status' => 1,
                    'message' => '审核通过'
                ]);
            } else {
                if (isset($result['operaTrace']) && !empty($result['operaTrace'])) {
                    $query->where('operaTrace', $result['operaTrace'])->update(['audit_msg' => $result['auditMsg'], 'audit_status' => 1]);
                }
                $msg = "";
                //9-待处理；3-待审核；0-审核通过；X-审核失败；1-审核驳回；5-待签约
                switch ($result['auditStatus']) {
                    case "9":
                        $msg = "易生待处理";
                        break;
                    case "3":
                        $msg = "易生待审核";
                        break;
                    case "X":
                        $msg = "易生审核失败";
                        break;
                    case "1":
                        $msg = "易生审核驳回";
                        break;
                    case "5":
                        $msg = "易生待签约";
                        break;
                }
                DB::table('store_pay_ways')
                    ->where(['store_id' => $storeId, 'company' => $easypay_store->version])
                    ->update([
                        'status' => 3,
                        'status_desc' => $result['auditMsg'],
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ]);
                return json_encode([
                    'status' => 2,
                    'message' => "状态:" . $msg . "_原因：" . $result['auditMsg']
                ]);
            }
        }
    }

    public function info(Request $request)
    {
        $data = $request->all();
        $storeId = $data['store_id'];
        $easypay_config_obj = new EasyPayConfigController();
        $easypay_config = $easypay_config_obj->easypay_config($storeId);
        if (!$easypay_config) {
            return json_encode([
                'status' => 2,
                'message' => '易生支付配置不存在请检查配置'
            ]);
        }
        $easypay_store = EasypayStore::where('store_id', $storeId)
            ->select('mer_trace', 'audit_status')
            ->first();
        if (!$easypay_store) {
            return json_encode([
                'status' => 2,
                'message' => '未进件'
            ]);
        }
        $reqData = [
            'merTrace' => $easypay_store->mer_trace,
            'messageType' => 'QUERYMER',
            'clientCode' => $easypay_config->client_code,
            'version' => '1.0',
        ];

        $reqData['MAC'] = $this->sign($reqData);
        $result = json_decode($this->curl($reqData, $this->domain . self::APPLAY, ['Charset: UTF-8']), true);

    }


    public function updateImg($img, $picMode)
    {

        try {
            $data = [
                'version' => '1.0',
                'fileName' => $this->images_get($img),
                'clientCode' => self::$client_code,
                'picMode' => $picMode,
            ];

            $params = $data;
            unset($data['fileName']);
            $params['MAC'] = $this->sign($data);

//            $params['fileName'] = new \CURLFile($params['fileName']);
            $params['fileName'] = new \CURLFile($params['fileName'], mime_content_type($params['fileName']), basename($params['fileName']));

            $headers = ["Content-Type: multipart/form-data;"];

            $rs = json_decode($this->curl($params, $this->domain . self::IMG_UPDATE, $headers), true);

            Log::channel("easypay")->info("easypay-updateImg", [
                "url" => $this->domain . self::IMG_UPDATE,
                "param" => $params,
                "req" => $data,
                "res" => $rs
            ]);
            if (isset($rs['fileId']) && !empty($rs['fileId'])) {
                return $rs['fileId'];
            }
            return '';
        } catch (\Exception $ex) {
            echo $ex->getMessage();
        }
    }

    protected function getMillisecond()
    {
        list($s1, $s2) = explode(' ', microtime());
        return (float)sprintf(' % .0f', (floatval($s1) + floatval($s2)) * 1000);

    }

    public function images_get($img_url)
    {
        return UploadImgUtil::images_get($img_url);
    }

    public function curl($params, $url, $headers)
    {
        try {
            $ch = curl_init();

            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

            if (!empty($headers)) {
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            }

            $result = curl_exec($ch);
            if (curl_errno($ch)) {
                echo 'Error:' . curl_error($ch);
            }
            curl_close($ch);

            return $result;
        } catch (\Exception $ex) {
            echo $ex->getMessage();
        }
    }

    public function sign(array $params): string
    {
        ksort($params);
        $stringToBeSigned = "";
        foreach ($params as $k => $v) {

            if (is_array($v)) {
                $v = json_encode($v);
            }
            $stringToBeSigned .= $k . "=" . $v . "&";
        }
        $stringToBeSigned = rtrim($stringToBeSigned, "&");

        $sign = strtoupper(md5($stringToBeSigned . '&key=' . self::$key));
        Log::channel("easypay")->info("sign-string", [
            "params" => $params,
            "str" => $stringToBeSigned . '&key=' . self::$key,
            "sign" => $sign
        ]);
        return $sign;
//        return strtoupper(md5($stringToBeSigned . '&key=' . self::$key));
    }


    protected function EasyPayTimeFormat($start_time, $end_time)
    {
        if ($start_time) {
            $start_time = str_replace('-', '.', $start_time);
        } else {
            $start_time = '';
        }

        if ($end_time) {
            if ($end_time == '长期') {
                $end_time = '2999.12.31';
            } else {
                $end_time = str_replace('-', '.', $end_time);
            }
        } else {
            $end_time = '';
        }
        Log::channel("easypay")->info("EasyPayTimeFormat", [$start_time, $end_time]);
        return [$start_time, $end_time];
    }

    //通过支行名称获取银行地区码
    protected function getCityCodeBySubBankName($name)
    {
        if (!$name) {
            return [
                'status' => '0',
                'message' => '银行名称不存在'
            ];
        }

        $bank_infos = BankInfo::where('bankName', $name)
            ->first();
        if ($bank_infos) {
            return [
                'status' => '1',
                'message' => '查询成功',
                'data' => $bank_infos
            ];
        } else {
            return [
                'status' => '0',
                'message' => '银行名称未找到'
            ];
        }
    }


    public function v2sign($reqHeader, $params, $priKey)
    {
        ksort($params);
        ksort($reqHeader);
        $str = json_encode($reqHeader) . strtoupper(md5(json_encode($params)));
        $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($priKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";

        ($res) or die('您使用的私钥格式错误，请检查RSA私钥配置');

        openssl_sign($str, $sign, $res, OPENSSL_ALGO_SHA256);

        $sign = base64_encode($sign);
        return $sign;

    }

    public function act_query($reqBody, $priKey)
    {

        return $this->v2curl($reqBody, self::DOMAIN_LIANHE . self::ACT_QUERY, ['Content-Type: application/json'], $priKey);
    }

    public function apply_query($reqBody, $priKey)
    {
        return $this->v2curl($reqBody, $this->domain . self::APPLY_QUERY, ['Content-Type: application/json'], $priKey);
    }

    public function v2curl($reqBody, $url, $headers, $priKey)
    {
        try {
            $ch = curl_init();
            $reqHeader = [
                'transTime' => date('YmdHis'),
                'reqId' => $reqBody['reqId']
            ];
            unset($reqBody['reqId']);
            $params = json_encode([
                'reqHeader' => $reqHeader,
                'reqSign' => $this->v2sign($reqHeader, $reqBody, $priKey),
                'reqBody' => $reqBody
            ]);
//            error_log(date('Y-m-d H:i:s') . " 【易生联合收单Request】： " . $params . "\n\n", 3, "/tmp/" . 'easypay-act' . date('Ymd') . ".log");
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

            $result = curl_exec($ch);
            if (curl_errno($ch)) {
                echo 'Error:' . curl_error($ch);
            }
            curl_close($ch);
            Log::channel("easypay")->info("act_query", [
                "url" => $url,
                "req" => $reqBody,
                "params" => json_decode($params, true),
                "header" => $headers,
                "result" => $result
            ]);
//            error_log(date('Y-m-d H:i:s') . " 【易生联合收单Response】： " . $result . "\n\n", 3, "/tmp/" . 'easypay-act' . date('Ymd') . ".log");
            return $result;
        } catch (\Exception $ex) {
            echo $ex->getMessage() . $ex->getLine();
        }
    }


}
